package org.jeecg.modules.api.wlhy.customer;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.aspect.annotation.EntityDict;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.middleware.rabbitmq.gen.EnumGenHandler;
import org.jeecg.modules.middleware.rabbitmq.gen.GenMqUtil;
import org.jeecg.modules.wlhy.customer.entity.HyCustomer;
import org.jeecg.modules.wlhy.customer.service.IHyCustomerService;
import org.jeecg.modules.wlhy.hydriver.entity.HyDriver;
import org.jeecg.modules.wlhy.hydriver.service.IHyDriverService;
import org.jeecg.modules.wlhy.setting.service.IHySettingService;
import org.jeecg.modules.wlhy.shipping.constant.ShippingStatus;
import org.jeecg.modules.wlhy.shipping.entity.HyShippingNote;
import org.jeecg.modules.wlhy.shipping.entity.HyShippingNoteDTO;
import org.jeecg.modules.wlhy.shipping.entity.ShippingNoteReq;
import org.jeecg.modules.wlhy.shipping.service.IHyShippingNoteService;
import org.jeecg.modules.wlhy.utils.UserUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Api(tags="货主运单")
@RestController
@RequestMapping("/api/wlhy/customer/shipping")
@Slf4j
public class ApiCustomerShippingController extends JeecgController<HyCustomer, IHyCustomerService> {

    private static final Logger LOGGER = LoggerFactory.getLogger(ApiCustomerShippingController.class);

   @Autowired
   private IHyCustomerService hyCustomerService;

    @Autowired
    private IHyShippingNoteService hyShippingNoteService;

    @Autowired
    private IHyDriverService hyDriverService;

//    @Autowired private PublisherRedisMessageService publisherRedisMessageService;

    @Autowired private IHySettingService settingService;


    @ApiOperation(value="货主运单分页列表查询", notes="货主运单分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(HyShippingNote hyShippingNote,
                                   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                   HttpServletRequest req) {
        HyCustomer hyCustomer  = hyCustomerService.getCustomer(req);
        String customerId = hyCustomer.getId();
        QueryWrapper<HyShippingNote> queryWrapper = QueryGenerator.initQueryWrapper(hyShippingNote, req.getParameterMap());
        queryWrapper.eq("customer_id",customerId);
        Page<HyShippingNote> page = new Page<HyShippingNote>(pageNo, pageSize);
        IPage<HyShippingNote> pageList = hyShippingNoteService.page(page, queryWrapper);
        return Result.OK(pageList);
    }


    @ApiOperation(value="货主运单分页列表关键词查询", notes="货主运单分页列表关键词查询")
    @GetMapping(value = "/listbykeyword")
    public Result<?> queryPageListByKeyword(
            @RequestParam(name="keyword") String keyword,
            @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
            @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
            HttpServletRequest req) {
        HyCustomer hyCustomer  = hyCustomerService.getCustomer(req);

        String customerId = hyCustomer.getId();
        QueryWrapper<HyShippingNoteDTO> queryWrapper =  new QueryWrapper<>();
        queryWrapper.eq("hy_shipping_note.customer_id",customerId);
        queryWrapper.and(
                qw -> qw.like("d.driver_name", keyword)
                        .or().like("v.vehicle_number", keyword)
                        .or().like("hy_shipping_note.shipping_note_number", keyword)
        );

        queryWrapper.orderByDesc("hy_shipping_note.create_time");
        Page<HyShippingNoteDTO> page = new Page<>(pageNo, pageSize);
        IPage<HyShippingNoteDTO> pageList = hyShippingNoteService.getPageList(page, queryWrapper);

        return Result.OK(pageList);
    }


    @ApiOperation(value="货主运单分页列表时间排序查询", notes="货主运单分页列表时间排序查询")
    @PostMapping(value = "/listbydatetime")
    public Result<?> queryPageListByTime(@RequestBody @Valid
            ShippingNoteReq shippingNoteReq,
            @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
            @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
            HttpServletRequest req) {
        HyCustomer hyCustomer  = hyCustomerService.getCustomer(req);

        String customerId = hyCustomer.getId();

        checkShippingReq(shippingNoteReq);

        QueryWrapper<HyShippingNote> queryWrapper =  new QueryWrapper<>();
        queryWrapper.eq("customer_id",customerId);

        queryWrapper.eq("order_id",shippingNoteReq.getOrderId());
        queryWrapper.eq("shipping_status",shippingNoteReq.getShippingStatus());


        if(StringUtils.isNotEmpty(shippingNoteReq.getStartTime())){
            queryWrapper.ge("hy_shipping_note."+shippingNoteReq.getOrderField(),shippingNoteReq.getStartTime()+" 00:00:00");
        }
        if(StringUtils.isNotEmpty(shippingNoteReq.getEndTime() )){
            queryWrapper.le("hy_shipping_note."+shippingNoteReq.getOrderField(),shippingNoteReq.getEndTime()+" 23:59:59" );
        }

        if(shippingNoteReq.getOrderType().equals("asc")){
            queryWrapper.orderByAsc(shippingNoteReq.getOrderField());
        }else {
            queryWrapper.orderByDesc(shippingNoteReq.getOrderField());
        }
        Page<HyShippingNote> page = new Page<HyShippingNote>(pageNo, pageSize);
        IPage<HyShippingNote> pageList = hyShippingNoteService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    private void checkShippingReq(ShippingNoteReq shippingNoteReq) {

        if(StringUtils.isEmpty(shippingNoteReq.getOrderId())){
            throw new JeecgBootException("货源ID不允许为空");
        }

        if(StringUtils.isEmpty(shippingNoteReq.getOrderField())){
            throw new JeecgBootException("排序字段不允许为空");
        }
        if(StringUtils.isEmpty(shippingNoteReq.getOrderType())){
            throw new JeecgBootException("排序类型不允许为空");
        }
        if(StringUtils.isEmpty(shippingNoteReq.getShippingStatus())){
            throw new JeecgBootException("运单状态不允许为空");
        }
        if(StringUtils.isEmpty(shippingNoteReq.getStartTime())){
            throw new JeecgBootException("开始时间不允许为空");
        }
        if(StringUtils.isEmpty(shippingNoteReq.getEndTime())){
            throw new JeecgBootException("结束时间不允许为空");
        }

        String as = "status_dt_receive,status_dt_loading,status_dt_unloading,status_dt_sign,pay_dt";
        int result = as.indexOf(shippingNoteReq.getOrderField());
        if(StringUtils.isNotEmpty(shippingNoteReq.getOrderField()) && result == -1){
            throw new JeecgBootException("排序字段不正确！");
        }
        String orderType = "asc,desc";
        int result1 = orderType.indexOf(shippingNoteReq.getOrderType());
        if(StringUtils.isNotEmpty(shippingNoteReq.getOrderType()) && result1 == -1){
            throw new JeecgBootException("排序类型不正确！");
        }
        String statusString = "0,1,2,3,4,5,8";
        int result2 = statusString.indexOf(shippingNoteReq.getShippingStatus());
        if(StringUtils.isNotEmpty(shippingNoteReq.getShippingStatus()) && result2 == -1){
            throw new JeecgBootException("运单状态不正确！");
        }

        Date startTime = DateUtils.getStrToDate(shippingNoteReq.getStartTime());
        if(startTime == null){
            throw new JeecgBootException("开始日期有效期格式错误,请重新填写!");
        }

        Date endTime = DateUtils.getStrToDate(shippingNoteReq.getEndTime());
        if(endTime == null){
            throw new JeecgBootException("开始日期有效期格式错误,请重新填写!");
        }
        if(endTime.before(startTime)){
            throw new JeecgBootException("结束日期不能在开始日期之前!");
        }
    }

    @ApiOperation(value="货主运单分页列表查询", notes="货主运单分页列表查询")
    @GetMapping(value = "/listCount2")
    public Result<?> queryPageListCount2(
            @RequestParam(name = "id") String id,
            HttpServletRequest req) {
        HyCustomer hyCustomer  = hyCustomerService.getCustomer(req);
        String customerId = hyCustomer.getId();
        QueryWrapper<HyShippingNote> queryWrapper = new QueryWrapper<>();
        QueryWrapper<HyShippingNote> queryWrapper3 = new QueryWrapper<>();
        QueryWrapper<HyShippingNote> queryWrapper4 = new QueryWrapper<>();
        QueryWrapper<HyShippingNote> queryWrapper5 = new QueryWrapper<>();
        QueryWrapper<HyShippingNote> queryWrapper6 = new QueryWrapper<>();
        QueryWrapper<HyShippingNote> queryWrapper7 = new QueryWrapper<>();
        QueryWrapper<HyShippingNote> queryWrapper8 = new QueryWrapper<>();
        QueryWrapper<HyShippingNote> queryWrapper9 = new QueryWrapper<>();


        if(!StringUtils.isEmpty(id)){
            queryWrapper.eq("order_id",id);
            queryWrapper3.eq("order_id",id);
            queryWrapper4.eq("order_id",id);
            queryWrapper5.eq("order_id",id);
            queryWrapper6.eq("order_id",id);
            queryWrapper7.eq("order_id",id);
            queryWrapper8.eq("order_id",id);
            queryWrapper9.eq("order_id",id);

        }


        queryWrapper.eq("customer_id",customerId);
        queryWrapper.eq("shipping_status","1");
        int count = hyShippingNoteService.count(queryWrapper);//已接单



        queryWrapper3.eq("customer_id",customerId);
        queryWrapper3.eq("shipping_status","3");
        int count3 = hyShippingNoteService.count(queryWrapper3);//运输中

        queryWrapper4.eq("customer_id",customerId);
        queryWrapper4.eq("shipping_status","4");
        int count4 = hyShippingNoteService.count(queryWrapper4);//已交货

        queryWrapper5.eq("customer_id",customerId);
        queryWrapper5.eq("shipping_status","5");
        int count5 = hyShippingNoteService.count(queryWrapper5);//已签收

        queryWrapper6.eq("customer_id",customerId);
        queryWrapper6.eq("shipping_status","5");
        queryWrapper6.eq("shipping_pay_status","2");
        int count6 = hyShippingNoteService.count(queryWrapper6);//已对账

        queryWrapper7.eq("customer_id",customerId);
        queryWrapper7.eq("shipping_status","5");
        queryWrapper7.eq("shipping_pay_status","3");
        int count7 = hyShippingNoteService.count(queryWrapper7);//待审核

        queryWrapper8.eq("customer_id",customerId);
        queryWrapper8.eq("shipping_status","5");
        queryWrapper8.eq("shipping_pay_status","4");
        int count8 = hyShippingNoteService.count(queryWrapper8);//待支付

        queryWrapper9.eq("customer_id",customerId);
        queryWrapper9.eq("shipping_status","5");
        queryWrapper9.eq("shipping_pay_status","6");
        int count9 = hyShippingNoteService.count(queryWrapper9);//已支付
        Map map=new HashMap<>();
        map.put("yjd",count);
        map.put("ysz",count3);
        map.put("yjh",count4);
        map.put("yqs",count5);

        map.put("ydz",count6);
        map.put("dsh",count7);
        map.put("dzf",count8);
        map.put("yzf",count9);

        return Result.OK(map);
    }

    @ApiOperation(value="货主运单分页列表查询", notes="货主运单分页列表查询")
    @GetMapping(value = "/listCount")
    public Result<?> queryPageListCount(

                                   HttpServletRequest req) {
        HyCustomer hyCustomer  = hyCustomerService.getCustomer(req);
        String customerId = hyCustomer.getId();
        QueryWrapper<HyShippingNote> queryWrapper = new QueryWrapper<>();
        QueryWrapper<HyShippingNote> queryWrapper3 = new QueryWrapper<>();
        QueryWrapper<HyShippingNote> queryWrapper4 = new QueryWrapper<>();
        QueryWrapper<HyShippingNote> queryWrapper5 = new QueryWrapper<>();
        QueryWrapper<HyShippingNote> queryWrapper6 = new QueryWrapper<>();
        QueryWrapper<HyShippingNote> queryWrapper7 = new QueryWrapper<>();
        QueryWrapper<HyShippingNote> queryWrapper8 = new QueryWrapper<>();
        QueryWrapper<HyShippingNote> queryWrapper9 = new QueryWrapper<>();





        queryWrapper.eq("customer_id",customerId);
        queryWrapper.eq("shipping_status","1");
        int count = hyShippingNoteService.count(queryWrapper);//已接单



        queryWrapper3.eq("customer_id",customerId);
        queryWrapper3.eq("shipping_status","3");
        int count3 = hyShippingNoteService.count(queryWrapper3);//运输中

        queryWrapper4.eq("customer_id",customerId);
        queryWrapper4.eq("shipping_status","4");
        int count4 = hyShippingNoteService.count(queryWrapper4);//已交货

        queryWrapper5.eq("customer_id",customerId);
        queryWrapper5.eq("shipping_status","5");
        int count5 = hyShippingNoteService.count(queryWrapper5);//已签收

        queryWrapper6.eq("customer_id",customerId);
        queryWrapper6.eq("shipping_status","5");
        queryWrapper6.eq("shipping_pay_status","2");
        int count6 = hyShippingNoteService.count(queryWrapper6);//已对账

        queryWrapper7.eq("customer_id",customerId);
        queryWrapper7.eq("shipping_status","5");
        queryWrapper7.eq("shipping_pay_status","3");
        int count7 = hyShippingNoteService.count(queryWrapper7);//待审核

        queryWrapper8.eq("customer_id",customerId);
        queryWrapper8.eq("shipping_status","5");
        queryWrapper8.eq("shipping_pay_status","4");
        int count8 = hyShippingNoteService.count(queryWrapper8);//待支付

        queryWrapper9.eq("customer_id",customerId);
        queryWrapper9.eq("shipping_status","5");
        queryWrapper9.eq("shipping_pay_status","6");
        int count9 = hyShippingNoteService.count(queryWrapper9);//已支付
        Map map=new HashMap<>();
        map.put("yjd",count);
        map.put("ysz",count3);
        map.put("yjh",count4);
        map.put("yqs",count5);

        map.put("ydz",count6);
        map.put("dsh",count7);
        map.put("dzf",count8);
        map.put("yzf",count9);

        return Result.OK(map);
    }

    @AutoLog(value = "运单完结")
    @ApiOperation(value="运单完结", notes="运单完结")
    @PostMapping(value = "/shippingFinish")
    public Result<?> shippingFinish(@RequestBody JSONObject jsonObject, HttpServletRequest req) {
        HyCustomer hyCustomer  = hyCustomerService.getCustomer(req);
        String id = jsonObject.getString("id");
        if(StringUtils.isEmpty(id)){
            return  Result.error("运单信息获取错误");
        }

        HyShippingNote shippingNote = hyShippingNoteService.getById(id);

        if(shippingNote==null){
            return  Result.error("运单信息不存在");
        }
        if(!"4".equals(shippingNote.getShippingStatus())){
            return Result.error("运单状态信息错误");
        }

        if(!StringUtils.equals(hyCustomer.getId(),shippingNote.getCustomerId())){
            return Result.error("运单信息错误");
        }

        String strgoodsWeightLoading = jsonObject.getString("goodsWeightLoading");
        String imgLoading = jsonObject.getString("imgLoading");


        if(!StringUtils.isEmpty(imgLoading)){
            shippingNote.setImgLoading(imgLoading);
        }

        if(!StringUtils.isEmpty(strgoodsWeightLoading)){
            BigDecimal goodsWeightLoading = null;
            try{
                goodsWeightLoading = new BigDecimal(strgoodsWeightLoading);
                shippingNote.setGoodsWeightLoading(goodsWeightLoading);
            }catch (Exception e){
                return  Result.error("装货量格式错误");
            }
        }

        String strgoodsWeightUnloading = jsonObject.getString("goodsWeightUnloading");
        String imgUnloading = jsonObject.getString("imgUnloading");
        if(!StringUtils.isEmpty(strgoodsWeightUnloading)){
            BigDecimal goodsWeightUnloading = null;
            try{
                goodsWeightUnloading = new BigDecimal(strgoodsWeightUnloading);
                shippingNote.setGoodsWeightUnloading(goodsWeightUnloading);
            }catch (Exception e){
                return  Result.error("装货量格式错误");
            }
        }
        if(!StringUtils.isEmpty(imgUnloading)){
            shippingNote.setImgUnloading(imgUnloading);
        }


        if(shippingNote.getGoodsWeightLoading() == null){
            return  Result.error("装货数量不能为空");
        }
        if("1".equals(settingService.getSettingValueByTag2("usedLoadingImg"))) {
            if (StringUtils.isEmpty(shippingNote.getImgLoading())) {
                return Result.error("装货凭证照片不能为空");
            }
        }


        if(shippingNote.getGoodsWeightUnloading() == null){
            return  Result.error("卸货数量不能为空");
        }
        if("1".equals(settingService.getSettingValueByTag2("usedUnLoadingImg"))) {
            if (StringUtils.isEmpty(shippingNote.getImgUnloading())) {
                return Result.error("卸货凭证照片不能为空");
            }
        }

//        //检查油气
//        if("1".equals(shippingNote.getIzUsedGas())) {
//            HyShippingNoteGas gas = hyShippingNoteGasService.getByShippingId(shippingNote.getId());
//            if (gas != null) {
//                String gasStatus = gas.getGasStatus();
//                if ("1".equals(gasStatus)) {
//                    return Result.error("油气结算暂未完成,请稍后重试!");
//                }
//            }
//        }

        //核算
        hyShippingNoteService.calcCoss(shippingNote);

        shippingNote.setShippingStatus(ShippingStatus.已签收.getValue());//设置状态为已交货
        shippingNote.setStatusDtSign(new Date());//货源完结时间

        shippingNote.setShippingPayStatus("1"); //申请对账
        shippingNote.setPayDtSubmitCheck(new Date());//申请对账时间

        String realName = UserUtil.getLoginUser().getRName();
        shippingNote.setQsr(realName);//设置签收人


        hyShippingNoteService.updateById(shippingNote);
        //签收订阅消息
        if( "1".equals(shippingNote.getTosIdentification())){
            GenMqUtil.sendMsg(EnumGenHandler.SHIPPING_DISCHARGE, "TosApi" , shippingNote);
        }

        return Result.OK(shippingNote);
    }

//    @AutoLog(value = "APP货主管理-获取司机信息")
    @ApiOperation(value="APP货主管理-获取司机信息", notes="APP货主管理-获取司机信息")
    @GetMapping(value = "/getDriverInfo")
    @EntityDict
    public Result<?> getDriverInfo( @RequestParam(name = "id") String id,HttpServletRequest req ) {
        hyCustomerService.getCustomer(req);
        HyDriver driver =   hyDriverService.getById(id);
        return Result.OK(driver);
    }
}
